package mgodb

import (
	"fmt"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/service/mongo"
	"time"

	"github.com/facebookgo/inject"
	"github.com/globalsign/mgo"
	"github.com/globalsign/mgo/bson"
	"github.com/pkg/errors"
)

// cMenu 菜单管理表名
const cMenu = "oper_menu"

// Menu 菜单管理
type Menu struct {
	DB *mongo.DB
}

// Init 初始化
func (a *Menu) Init(g *inject.Graph, db *mongo.DB) {
	a.DB = db

	// 初始化mongo索引
	a.DB.C(cMenu, func(c *mgo.Collection) error {
		c.EnsureIndex(mgo.Index{
			Key:    []string{"record_id"},
			Unique: true,
		})
		c.EnsureIndexKey("deleted")
		c.EnsureIndexKey("status")
		c.EnsureIndexKey("level_code")
		c.EnsureIndexKey("deleted", "status", "level_code")
		c.EnsureIndexKey("deleted", "status", "code", "type")
		return nil
	})

	var val model.IMenu = a
	g.Provide(&inject.Object{Value: val, Name: "IMenu"})
}

// QueryPage 查询分页数据
func (a *Menu) QueryPage(params schema.MenuQueryParam, pageIndex, pageSize uint) (int64, []*schema.Menu, error) {
	query := bson.M{
		"deleted": 0,
	}

	if v := params.Type; v != 0 {
		query["type"] = v
	}

	if v := params.ParentID; v != "" {
		item, _ := a.Get(v)
		if item != nil {
			query["level_code"] = bson.M{"$regex": fmt.Sprintf("^%s.+", item.LevelCode)}
		}
	}

	if v := params.Status; v != 0 {
		query["status"] = v
	}

	if v := params.Name; v != "" {
		query["name"] = bson.M{"$regex": v}
	}

	var total int64
	var items []*schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		total = int64(n)
		if total == 0 {
			return nil
		}

		return c.Find(query).Sort("type", "sequence").Skip(int((pageIndex - 1) * pageSize)).Limit(int(pageSize)).All(&items)
	})
	if err != nil {
		return 0, nil, errors.Wrapf(err, "查询分页数据发生错误")
	}

	return total, items, nil
}

// QuerySelect 查询选择数据
func (a *Menu) QuerySelect(params schema.MenuSelectParam) ([]*schema.MenuSelect, error) {
	query := bson.M{
		"deleted": 0,
	}

	if v := params.Status; v != 0 {
		query["status"] = v
	}

	if v := params.Name; v != "" {
		query["name"] = bson.M{"$regex": v}
	}

	var items []*schema.MenuSelect
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(query).Sort("sequence").All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "查询选择数据发生错误")
	}
	return items, nil
}

// QueryByParentIDOrderLevelCode 根据上级查询数据
func (a *Menu) QueryByParentIDOrderLevelCode(parentID string) ([]*schema.Menu, error) {
	query := bson.M{
		"deleted":   0,
		"parent_id": parentID,
	}

	var items []*schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(query).Sort("level_code").All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "根据上级查询数据发生错误")
	}

	return items, nil
}

// Get 精确查询数据
func (a *Menu) Get(recordID string) (*schema.Menu, error) {
	var item schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(bson.M{"record_id": recordID}).One(&item)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrapf(err, "精确查询数据发生错误")
	}
	return &item, nil
}

// CheckChild 检查下级菜单
func (a *Menu) CheckChild(parentID string) (bool, error) {
	var exists bool
	query := bson.M{
		"deleted":   0,
		"parent_id": parentID,
	}

	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		exists = n > 0
		return nil
	})
	if err != nil {
		return false, errors.Wrapf(err, "检查下级菜单发生错误")
	}

	return exists, nil
}

// CheckCode 检查编号是否存在
func (a *Menu) CheckCode(code string, typ int, parentID string) (bool, error) {
	var exists bool
	query := bson.M{
		"deleted":   0,
		"code":      code,
		"type":      typ,
		"parent_id": parentID,
	}

	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		n, err := c.Find(query).Count()
		if err != nil {
			return err
		}
		exists = n > 0
		return nil
	})
	if err != nil {
		return false, errors.Wrapf(err, "检查编号是否存在发生错误")
	}

	return exists, nil
}

// GetByCodeAndType 根据编号和类型查询数据
func (a *Menu) GetByCodeAndType(code string, typ int) (*schema.Menu, error) {
	var item schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(bson.M{"deleted": 0, "status": 1, "code": code, "type": typ}).One(&item)
	})
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, errors.Wrapf(err, "根据编号和类型查询数据发生错误")
	}
	return &item, nil
}

// QueryChildsByLevelCode 根据分级码查询下级数据
func (a *Menu) QueryChildsByLevelCode(levelCode string) ([]*schema.Menu, error) {
	query := bson.M{
		"deleted":    0,
		"status":     1,
		"level_code": bson.M{"$regex": fmt.Sprintf("^%s.+", levelCode)},
	}

	var items []*schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(query).Sort("sequence").All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "查询选择数据发生错误")
	}
	return items, nil
}

// QueryLevelCodesByLevelCodeAndIDs 根据分级码和ID列表查询下级分级码列表
func (a *Menu) QueryLevelCodesByLevelCodeAndIDs(levelCode string, recordIDs []string) ([]string, error) {
	query := bson.M{
		"deleted":    0,
		"status":     1,
		"level_code": bson.M{"$regex": fmt.Sprintf("^%s.+", levelCode)},
	}
	if len(recordIDs) > 0 {
		query["record_id"] = bson.M{"$in": recordIDs}
	}

	var levelCodes []string
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(query).Distinct("level_code", &levelCodes)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "根据分级码和ID列表查询下级分级码列表发生错误")
	}
	return levelCodes, nil
}

// QueryByLevelCodes 根据分级码查询数据
func (a *Menu) QueryByLevelCodes(levelCodes []string) ([]*schema.Menu, error) {
	query := bson.M{
		"deleted":    0,
		"status":     1,
		"level_code": bson.M{"$in": levelCodes},
	}

	var items []*schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(query).Sort("sequence").All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "根据分级码查询数据发生错误")
	}
	return items, nil
}

// Create 创建数据
func (a *Menu) Create(item *schema.Menu) error {
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		id, err := a.DB.IncrID(cMenu)
		if err != nil {
			return err
		}
		item.ID = id
		return c.Insert(item)
	})
	if err != nil {
		return errors.Wrapf(err, "创建数据发生错误")
	}

	return nil
}

// Update 更新数据
func (a *Menu) Update(recordID string, info map[string]interface{}) error {
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "更新数据发生错误")
	}
	return nil
}

// Delete 删除数据
func (a *Menu) Delete(recordID string) error {
	info := map[string]interface{}{
		"deleted": time.Now().Unix(),
	}
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Update(bson.M{"record_id": recordID}, bson.M{"$set": info})
	})
	if err != nil {
		return errors.Wrapf(err, "删除数据发生错误")
	}
	return nil
}

// UpdateLevelCode 更新分级码数据
func (a *Menu) UpdateLevelCode(src, target string) error {
	query := bson.M{
		"deleted":    0,
		"level_code": bson.M{"$regex": "^" + src},
	}

	var items []*schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(query).Sort("level_code").All(&items)
	})
	if err != nil {
		return errors.Wrapf(err, "更新分级码数据发生错误")
	}

	err = a.DB.C(cMenu, func(c *mgo.Collection) error {
		b := c.Bulk()

		for _, item := range items {
			levelCode := target
			if len(item.LevelCode) > len(target) {
				levelCode = fmt.Sprintf("%s%s", levelCode, []byte(item.LevelCode)[len(target):])
			}
			b.Update(bson.M{"_id": item.ID}, bson.M{"$set": bson.M{"level_code": levelCode}})
		}

		_, verr := b.Run()
		return verr
	})
	if err != nil {
		return errors.Wrapf(err, "更新分级码数据发生错误")
	}

	return nil
}

// QueryByIDs 根据ID列表查询菜单数据
func (a *Menu) QueryByIDs(recordIDs []string) ([]*schema.Menu, error) {
	query := bson.M{
		"deleted":   0,
		"status":    1,
		"record_id": bson.M{"$in": recordIDs},
	}

	var items []*schema.Menu
	err := a.DB.C(cMenu, func(c *mgo.Collection) error {
		return c.Find(query).All(&items)
	})
	if err != nil {
		return nil, errors.Wrapf(err, "根据ID列表查询菜单数据发生错误")
	}

	return items, nil
}
